import zmq


def main():
    ctx = zmq.Context.instance()
    frontend = ctx.socket(zmq.SUB)
    frontend.connect("tcp://localhost:5557")
    backend = ctx.socket(zmq.XPUB)
    backend.bind("tcp://*:5558")

    frontend.setsockopt(zmq.SUBSCRIBE, b"")

    cache = {}

    poller = zmq.Poller()
    poller.register(frontend, zmq.POLLIN)
    poller.register(backend, zmq.POLLIN)

    while True:
        try:
            events = dict(poller.poll(1000))
        except KeyboardInterrupt:
            print("interrupted")
            break

        if frontend in events:
            msg = frontend.recv_multipart()
            print("frontend recv msg:", msg)
            topic, current = msg
            cache[topic] = current
            backend.send_multipart(msg)

        if backend in events:
            event = backend.recv()
            print("backend recv msg:", event)
            if event.startswith(b"\x01"):
                topic = event[1:]
                if topic in cache:
                    print("Sending cache topic %s" % topic)
                    backend.send_multipart([topic, cache[topic]])


if __name__ == "__main__":
    main()
